﻿using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;

namespace TianShiProject.IFileCommonServices
{
    public class FileCommonApp : ApplicationService
    {
        private readonly IFileCommonService _fileCommonService;
        public FileCommonApp(IFileCommonService fileCommonService)
        {
            _fileCommonService = fileCommonService;
        }

        /// <summary>
        /// 上传一个文件，并返回文件上传成功后的信息
        /// </summary>
        /// <param name="File">要上传的文件实体</param>
        /// <returns>文件上传成功后返回的文件相关信息</returns>
        //public async Task<FileUploadOutputDto> UploadFile(IFormFile File)
        //{
        //    try
        //    {
        //        return await _fileCommonService.UploadFile(File);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw new UserFriendlyException("文件上传失败，原因" + ex.Message);
        //    }
        //}

        ///// <summary>
        ///// 简单上传-上传小文件
        ///// </summary>
        //public async Task<string> UploadFileQiNiu(string filme)
        //{
        //    try
        //    {
        //        return await _fileCommonService.UploadFileQiNiu(filme);
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }
        //}

        /// <summary>
        /// 上传七牛云
        /// /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public string Uplosdqiniu(IFormFile file)
        {
            try
            {
                //密钥
                var mac = new Mac("hrGZuiprXwlp5U59A1xbVTE6LzRS1wQbbc4bRuFa", "34Rtybu5AOGCFeRoDq6vyvhqZek1vbOKgHuPZNd6");
                var ex = Path.GetExtension(file.FileName);//后缀
                if (!(ex != null || !((IList)FileTypes.FileType).Contains(ex.ToLower()))) return String.Empty;

                var key = $"{file.FileName}/{DateTime.Now.Year}/{DateTime.Now:yyyyMMddHHmmssfff}{ex}";
                //七牛云库的名称
                var bucket = "img1s";

                PutExtra extra = new PutExtra();
                PutPolicy putPolicy = new PutPolicy { Scope = bucket };

                // 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖)，请使用 SCOPE = "BUCKET:KEY"
                    // putPolicy.Scope = bucket + ":" + saveKey;
                //    putPolicy.Scope = bucket;
                putPolicy.SetExpires(3600);
                // 上传到云端多少天后自动删除该文件，如果不设置（即保持默认默认）则不删除
                putPolicy.DeleteAfterDays = 40;

                var token = Qiniu.Util.Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
                Config config = new Config
                {
                    UseHttps = true,
                    UseCdnDomains = true,
                    ChunkSize = ChunkUnit.U512K,

                };
                
                FormUploader target = new FormUploader(config);
                HttpResult result = target.UploadStream(file.OpenReadStream(), key, token, extra);
                //七牛云库的路径
                if (result.Code == 200) return "http://r5vuofi95.hb-bkt.clouddn.com/" + key;

            }
            catch (Exception)
            {

                return String.Empty;
            }

            return String.Empty;
        }

        public static class FileTypes
        {
            public static readonly string[] FileType = { ".jpg", ".png", ".jpeg", ".gif", ".bmp", };
        }


    }
}

